<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="省份" prop="province">
        <el-select v-model="queryParams.province" clearable placeholder="请选择省份" @change="handleProvinceChange" style="width: 150px;">
          <el-option v-for="province in provinceOptions" :key="province" :label="province" :value="province" />
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-select v-model="queryParams.city" clearable placeholder="请选择市" @change="handleCityChange" style="width: 150px;">
          <el-option v-for="city in cityOptions" :key="city" :label="city" :value="city" />
        </el-select>
      </el-form-item>
      <el-form-item label="县/区" prop="district">
        <el-select v-model="queryParams.district" clearable placeholder="请选择县/区" style="width: 150px;">
          <el-option v-for="district in districtOptions" :key="district" :label="district" :value="district" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['race:region:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['race:region:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['race:region:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" align="center" width="80" />
      <el-table-column label="省份" prop="province" align="center" />
      <el-table-column label="市" prop="city" align="center" />
      <el-table-column label="县/区" prop="district" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['race:region:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['race:region:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="省份" prop="province">
          <el-select v-model="form.province" placeholder="请选择省份" @change="handleFormProvinceChange" style="width: 100%;">
            <el-option v-for="province in provinceOptions" :key="province" :label="province" :value="province" />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="form.city" placeholder="请选择市" @change="handleFormCityChange" style="width: 100%;">
            <el-option v-for="city in formCityOptions" :key="city" :label="city" :value="city" />
          </el-select>
        </el-form-item>
        <el-form-item label="县/区" prop="district">
          <el-select v-model="form.district" placeholder="请选择县/区" style="width: 100%;">
            <el-option v-for="district in formDistrictOptions" :key="district" :label="district" :value="district" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue'
import { listRegion, getRegion, addRegion, updateRegion, delRegion, getProvinces, getCities, getDistricts } from '@/api/race/region'

const { proxy } = getCurrentInstance()

const list = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const open = ref(false)
const title = ref('')
const ids = ref([])
const single = ref(true)
const multiple = ref(true)

// 下拉选项
const provinceOptions = ref([])
const cityOptions = ref([])
const districtOptions = ref([])
const formCityOptions = ref([])
const formDistrictOptions = ref([])

const data = reactive({
  form: {
    id: undefined,
    province: undefined,
    city: undefined,
    district: undefined
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    province: undefined,
    city: undefined,
    district: undefined
  },
  rules: {
    province: [{ required: true, message: '请选择省份', trigger: 'change' }],
    city: [{ required: true, message: '请选择市', trigger: 'change' }],
    district: [{ required: true, message: '请选择县/区', trigger: 'change' }]
  }
})

const { form, queryParams, rules } = toRefs(data)

function getList() {
  loading.value = true
  listRegion(queryParams.value).then(res => {
    list.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    id: undefined,
    province: undefined,
    city: undefined,
    district: undefined
  }
  formCityOptions.value = []
  formDistrictOptions.value = []
  proxy.resetForm('formRef')
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value.province = undefined
  queryParams.value.city = undefined
  queryParams.value.district = undefined
  cityOptions.value = []
  districtOptions.value = []
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleAdd() {
  reset()
  open.value = true
  title.value = '新增地区'
}

function handleUpdate(row) {
  reset()
  const id = row.id || ids.value[0]
  getRegion(id).then(res => {
    form.value = res.data
    // 加载对应的市和县/区选项
    if (form.value.province) {
      loadFormCities(form.value.province)
      if (form.value.city) {
        loadFormDistricts(form.value.province, form.value.city)
      }
    }
    open.value = true
    title.value = '修改地区'
  })
}

function submitForm() {
  proxy.$refs['formRef'].validate(valid => {
    if (!valid) return
    const req = form.value.id ? updateRegion(form.value) : addRegion(form.value)
    req.then(() => {
      proxy.$modal.msgSuccess(form.value.id ? '修改成功' : '新增成功')
      open.value = false
      getList()
    })
  })
}

function handleDelete(row) {
  const delIds = row.id ? [row.id] : ids.value
  proxy.$modal.confirm('是否确认删除编号为"' + delIds.join(',') + '"的数据项？').then(() => {
    return delRegion(delIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

// 查询选项变化处理
function handleProvinceChange(province) {
  queryParams.value.city = undefined
  queryParams.value.district = undefined
  cityOptions.value = []
  districtOptions.value = []
  if (province) {
    loadCities(province)
  }
}

function handleCityChange(city) {
  queryParams.value.district = undefined
  districtOptions.value = []
  if (city && queryParams.value.province) {
    loadDistricts(queryParams.value.province, city)
  }
}

// 表单选项变化处理
function handleFormProvinceChange(province) {
  form.value.city = undefined
  form.value.district = undefined
  formCityOptions.value = []
  formDistrictOptions.value = []
  if (province) {
    loadFormCities(province)
  }
}

function handleFormCityChange(city) {
  form.value.district = undefined
  formDistrictOptions.value = []
  if (city && form.value.province) {
    loadFormDistricts(form.value.province, city)
  }
}

// 加载数据
function loadProvinces() {
  getProvinces().then(res => {
    provinceOptions.value = res.data
  })
}

function loadCities(province) {
  getCities(province).then(res => {
    cityOptions.value = res.data
  })
}

function loadDistricts(province, city) {
  getDistricts(province, city).then(res => {
    districtOptions.value = res.data
  })
}

function loadFormCities(province) {
  getCities(province).then(res => {
    formCityOptions.value = res.data
  })
}

function loadFormDistricts(province, city) {
  getDistricts(province, city).then(res => {
    formDistrictOptions.value = res.data
  })
}

onMounted(() => {
  loadProvinces()
  getList()
})
</script>
